/*
 * @Descripttion:
 * @version: 0.0.1
 * @Author: liutaotao
 * @Date: 2021-09-28 09:38:56
 * @LastEditors: liutaotao
 * @LastEditTime: 2021-10-12 21:52:52
 */
interface MZScrollOption {
  el?: string;
  topDistance?: number;
  bottomDistance?: number;
  [key: string]: any;
  callback?: () => {}
}


class MZScroll {
  mzOption = {
    el: 'body',
    topDistance: 100,
    bottomDistance: 100
  }
  el: Element;

  readonly screenHeight: number = window.innerHeight;
  constructor(option?: MZScrollOption) {
    this.mzOption = Object.assign(this.mzOption, option);
    this.el = document.querySelector(this.mzOption.el) as Element;
    this.init();
  }
  init() {
    this.classControler(true)
    let prevTop = 0
    this.el.addEventListener('scroll', (e: Event) => {
      let nextTop: number = (e.target as any).scrollTop
      let direction: boolean = nextTop > prevTop ? true : false;
      prevTop = nextTop;
      this.classControler(direction);
    });
  }
  classControler(direction: boolean) {
    let animateItems = this.el.querySelectorAll('[mz]');
    let bottomGap: number = this.screenHeight - this.el.getBoundingClientRect().bottom;
    bottomGap = bottomGap < 0 ? 0 : bottomGap;
    animateItems.forEach(el => {
      let elTop = el.getBoundingClientRect().top;
      let elBottom = el.getBoundingClientRect().bottom;
      let distance = this.screenHeight - bottomGap - this.mzOption.topDistance
      // 向下滚动
      if (direction && elTop <= distance) {
        el.classList.add('mz-animate');
      }
      // 向上滚动
      if (!direction && elBottom >= distance) {
        el.classList.remove('mz-animate');
      }
    })
  }
}

